home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 809 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.4 KB  |  48 lines

  1. Path: maverick.tad.eds.com!news-admin@tad.eds.com
  2. From: fignet05.darrins@eds.com (Darrin Smith)
  3. Newsgroups: comp.lang.c
  4. Subject: To malloc (new) or not to malloc?  When is the question.
  5. Date: 9 Jan 1996 14:54:59 GMT
  6. Organization: Somewhere in EDS...
  7. Message-ID: <4ctvk3$ort@maverick.tad.eds.com>
  8. NNTP-Posting-Host: 148.94.42.90
  9. Mime-Version: 1.0
  10. X-Newsreader: WinVN 0.93.11
  11.  
  12. I know that I should know the answer to this (I'm sure one of my past 
  13. instructors made it clear while I was sleep.... I mean sitting in class), 
  14. but I can't remember so...
  15.  
  16. Why is it that you can do something like the following:
  17.  
  18.      char *x;
  19.  
  20.      x="Some really long string with no particular meaning";
  21.  
  22. and have no problems, but can't (safely) do something like this:
  23.  
  24.     struct st1{char one[10];
  25.                    char two[20];
  26.                    char three[10];
  27.           };
  28.  
  29.     st1 *sptr;    //or struct st1 *sptr in C instead of C++
  30.  
  31.     sptr=fread(....);
  32.  
  33. This caused a program I was trying to debug to crash.  When I allocated 
  34. memory for sptr (I used sptr=new st1; but I suppose malloc would have done 
  35. just as well) it worked fine.                     
  36.  
  37.  
  38. What is going on here?  Why isn't memory set aside for st1 *sptr just as 
  39. it is for char *x?  Before I did the new (or malloc) it seemed as though 
  40. my program was getting written over!
  41.  
  42. Why?
  43.  
  44. Please respond here, or email me at: FIGNET05.darrins@eds.com
  45.  
  46. Thanks.
  47.  
  48.